package com.lv.suyiyong.hfrbusines.ui

import android.text.Editable
import android.text.TextWatcher
import android.text.method.PasswordTransformationMethod
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.ToastUtils
import com.lv.common.base.BaseActivity
import com.lv.common.dialog.SwipeCatpchaDialog
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.im.push.OfflineMessageDispatcher
import com.lv.common.imp.OnDialogSureListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.network.config.SP_KEY_USER_TOKEN
import com.lv.common.network.model.DataResult
import com.lv.common.utils.*
import com.lv.common.widget.textview.SpanTextView

import com.lv.service.model.ServiceViewModel
import com.lv.service.net.LoginByCodeReqBody
import com.lv.service.net.LoginByPassWordReqBody
import com.lv.service.net.SendCodeBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.webview.ConsealWebActivity
import com.lv.suyiyong.hfrbusines.R
import com.lv.suyiyong.hfrbusines.databinding.ActivityLoginBinding
import com.lv.suyiyong.hfrbusines.moudel.MainViewModel
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.system.exitProcess

/**
 * 作者： ygx
 * 创建日期：2023/5/31 4:12 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：密码登录
 */
@Route(path = ARoutUtils.LoginActivityURL)
class LoginActivity : BaseActivity<ActivityLoginBinding>(), View.OnClickListener {
    private var timer: TimerUnit? = null
    private val viewModel: MainViewModel by viewModel()
    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mIsCodeLogin = true
    private var isShowPassWord = false
    override fun getLayoutRes() = R.layout.activity_login
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)

        mBinding.apply {
            vm = viewModel
            isCodeLogin = mIsCodeLogin
            StatusBarUtil.setHeightAndPadding(this@LoginActivity, viewTop)
            tvForgotPwdLogin.setOnClickListener(this@LoginActivity)
            tvCode.setOnClickListener(this@LoginActivity)
            btnLogin.setOnClickListener(this@LoginActivity)
            btnCodeLogin.setOnClickListener(this@LoginActivity)
            ivEyes.setOnClickListener(this@LoginActivity)
            tvAgree.setOnClickListener(this@LoginActivity)
            etPhone.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//                    etPhone.paint.isFakeBoldText = !TextUtils.isEmpty(s)
                    if (s.length == 11) {
                        etCode.requestFocus()
                    }
                }

                override fun afterTextChanged(s: Editable) {
                }
            })

            mBinding.tvAgree.setText(
                createSpanTexts(),
                SpanTextView.SpanClickListener { position ->
                    ConsealWebActivity.openUrl(this@LoginActivity, "0")
                })
        }
    }


    override fun initConfig() {
        super.initConfig()
        OfflineMessageDispatcher.updateBadge(this, 0)

        UserDbHelper.deleteUserInfo(this@LoginActivity)
        //清除Token
        YgxUtilsKt.setAppToken("", "", "")
        TUILogin.logout(object : TUICallback() {
            override fun onSuccess() {}
            override fun onError(errorCode: Int, errorMessage: String) {}
        })
        V2TIMManager.getConversationManager().removeConversationListener(null)


    }

    private fun initLoginSate(res: UserInfo) {
        UserDbHelper.insertUserInfo(this@LoginActivity, res)
        SPStaticUtils.put(SP_KEY_USER_TOKEN, res.token)
//        SPStaticUtils.put(SP_KEY_USER_DUTY, res.duty)
//        SPStaticUtils.put(SP_KEY_USER_ISSALER, res.issaler)
        SPStaticUtils.put(Constants.SP_KEY_ADDRESS_PROVINCE, "")
        SPStaticUtils.put(Constants.SP_KEY_BOOK_ADDRESS_PROVINCE, "")

//        TIMAppService.getInstance().initBeforeLogin(0)
        // 在用户 UI 点击登录的时候调用
        TUILogin.login(
            this@LoginActivity,
            GenerateTestUserSig.SDKAPPID,
            res.txaccid,
            res.txaccidpassword,
            object : TUICallback() {
                override fun onError(code: Int, desc: String) {
                    LogUtils.e("onError")
                    showToast("登录失败，请联系业务员")
                }

                override fun onSuccess() {
                    LogUtils.e("onSuccess")
                    YgxUtilsKt.setAppToken(res.token, res.refreshtoken, res.id)
//                    YgxApplication.getInstance().registerPushManually()
                    YgxUtilsKt.sendMessgeToSelf(res.txaccid, res.phone)
                    ARouter.getInstance().build(ARoutUtils.HomeActivityURL)
                        .withParcelable("userInfo", res).navigation()
                    finish()
                }
            })
    }

    override fun initData() {
        super.initData()

    }

    private fun showSwipecaptDialog(phone: String) {
        val swipeCatpchaDialog =
            SwipeCatpchaDialog(this, true, true, object : OnDialogSureListener {
                override fun onSureClick(content: String?) {
                    val sendCode = YgxUtilsKt.sendCode(phone)
                    lifecycleScope.launchWhenCreated {
                        val result: DataResult<BaseYgxRsp> =
                            myScope.async {
                                serviceViewModel.sendCode(
                                    SendCodeBody(phone, sendCode)
                                )
                            }.await()
                        parseSendCodeResult(result)
                    }
                }
            })
        swipeCatpchaDialog.show()
    }

    private fun parseSendCodeResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (code == "200") {
                    if (timer == null) {
                        timer = TimerUnit(mBinding.tvCode)
                    }
                    timer?.startTime()
                    message?.let { message ->
                        showToast(this@LoginActivity, message)
                    }
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.tv_code -> {
                getCode()
            }

            R.id.btn_login -> {
                val account =
                    viewModel.obMobile.get() ?: return ToastUtils.showShort("手机号不能为空")
                val password =
                    viewModel.obPassword.get() ?: return ToastUtils.showShort("密码不能为空")
                val encode = DesUtil.encode(password)
                repoLogin(account, encode)
            }

            R.id.btn_code_login -> {
                val account =
                    viewModel.obMobile.get() ?: return ToastUtils.showShort("手机号不能为空")
                val password =
                    viewModel.obPasswordCon.get() ?: return ToastUtils.showShort("验证码不能为空")
                loginByCode(account, password)
            }

            R.id.tv_forgot_pwd_login -> {
                viewModel.obPassword.set("")
                mIsCodeLogin = !mIsCodeLogin
                mBinding.isCodeLogin = mIsCodeLogin
            }

            R.id.iv_eyes -> {
                isShowPassWord = !isShowPassWord
                val selectionStart = mBinding.etPassword.selectionStart
                if (isShowPassWord) {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_show_password)
                    mBinding.etPassword.transformationMethod = null
                } else {
                    mBinding.ivEyes.LoadSrc(com.lv.common.R.drawable.icon_close_eyes)
                    mBinding.etPassword.transformationMethod = PasswordTransformationMethod()
                }
                mBinding.etPassword.setSelection(selectionStart)
            }

            R.id.tv_agree -> {
                mBinding.cbBox.performClick()
            }

        }
    }

    private fun loginByCode(phone: String, sendCode: String) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    serviceViewModel.loginByCode(LoginByCodeReqBody(phone, sendCode))
                }.await()
            parseLoginResult(result)
        }
    }

    private fun repoLogin(phone: String, sendCode: String) {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async {
                    serviceViewModel.login(LoginByPassWordReqBody(phone, sendCode))
                }.await()
            parseLoginResult(result)
        }
    }

    private fun parseLoginResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                if (code == "200") {
                    data?.let { initLoginSate(it) }
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    private fun getCode() {
        val phone = viewModel.obMobile.get()
        if (phone.isNullOrEmpty() || phone.length < 11) {
            showToast(this@LoginActivity, "请输入11位手机号")
        } else {
            if (viewModel.obIsAgree.get() == true) {
                showSwipecaptDialog(phone)

            } else {
                showToast(this@LoginActivity, "请同意服务条款")
            }
        }
    }

    private fun createSpanTexts(): List<SpanTextView.BaseSpanModel>? {
        val spanModels: MutableList<SpanTextView.BaseSpanModel> = ArrayList()
        val textSpanModel = SpanTextView.TextSpanModel()
        textSpanModel.content = "我已经阅读并同意"
        spanModels.add(textSpanModel)
        val spanModel = SpanTextView.ClickSpanModel()
        spanModel.content = "《亨富然隐私政策》"
        spanModels.add(spanModel)
        return spanModels
    }

    override fun onBackPressed() {
        super.onBackPressed()
        exitProcess(0)
    }

    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exit() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else {
            exitProcess(0)
        }
    }


}